#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

int main(int argc,char* argv[])
{
    if(argc != 2)
    {
        exit(1);
    }
    //close(0);
    //close(1);
    //close(2);
    //int fd = open("log.txt", O_CREAT | O_WRONLY | O_APPEND, 0666);
    //int fd = open("log.txt", O_RDONLY);
    int fd = open(argv[1],O_RDONLY);
    if(fd < 0)
    {
        exit(1);
    }
    printf("fd = %d\n", fd);
    dup2(fd,0);
    close(fd);
    //dup2(fd,1); 
    while(1)
    {
        char buffer[64];
        if(!fgets(buffer,sizeof(buffer),stdin))
        {
            break;
        }
        printf("%s", buffer);
    }

    
    //默认向显示器输出
    //printf("hello mihayou\n");
    //printf("hello mihayou\n");
    //printf("hello mihayou\n");
    //fprintf(stdout, "hello stdout\n");
    //fprintf(stdout, "hello stdout\n");
    
    //umask(0);

    //printf("stdin = %d\n", stdin->_fileno);
    //printf("stdout = %d\n", stdout->_fileno);
    //printf("stderr = %d\n", stderr->_fileno);

    //int fd1 = open("log1.txt", O_CREAT | O_WRONLY | O_TRUNC, 0666);
    //int fd2 = open("log2.txt", O_CREAT | O_WRONLY | O_TRUNC, 0666);
    //int fd3 = open("log3.txt", O_CREAT | O_WRONLY | O_TRUNC, 0666);
    //int fd4 = open("log4.txt", O_CREAT | O_WRONLY | O_TRUNC, 0666);
    //if(fd1 < 0)
    //{
    //    exit(1);
    //}
    //if(fd2 < 0)
    //{
    //    exit(1);
    //}
    //if(fd3 < 0)
    //{
    //    exit(1);
    //}
    //if(fd4 < 0)
    //{
    //    exit(1);
    //}

    //printf("fd1 = %d\n",fd1);
    //printf("fd2 = %d\n",fd2);
    //printf("fd3 = %d\n",fd3);
    //printf("fd4 = %d\n",fd4);


    //打开一个文件，没有就新建,并且清空
    //int fd = open("log.txt", O_CREAT | O_WRONLY | O_TRUNC,0666);
    //追加打开文件
    //int fd = open("log.txt", O_CREAT | O_WRONLY | O_APPEND,0666);
    //读一个文件
    //int fd = open("log.txt", O_RDONLY);
    //if(fd < 0)
    //{
    //    perror("open fail");
    //    exit(1);
    //}

    //printf("fd = %d\n", fd);

    //while(1)
    //{
    //    char buffer[64];
    //    int n = read(fd,buffer,sizeof(buffer) - 1);
    //    if(n > 0)
    //    {
    //        buffer[n] = 0;
    //        printf("%s",buffer);
    //    }
    //    else if(n == 0)
    //    {
    //        break;
    //    }
    //}

    //const char* msg = "hello mihayou\n";
    //const char* msg = "abc\n";
    //int cnt = 5;
    //int a = 12345678;
    //while(cnt--)
    //{
    //    //当作字符来写
    //    
    //    char buffer[64];
    //    snprintf(buffer,sizeof(buffer),"%d", a);
    //    write(fd,buffer,strlen(buffer));

    //    //error 错误的写法 
    //    //write(fd,&a,sizeof(a));

    //    write(fd,msg,strlen(msg));
    //}
    //close(fd); 
    return 0;
}
